<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">




<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.4">







  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Swift社区" type="application/atom+xml" />






<meta name="description" content="在面向对象的编程中，抽象类型提供了一个基础实现，其他类型可以从中继承，以获得某种共享的、共同的功能。抽象类型与普通类型的区别在于，它们永远不会被当作原样使用（事实上，一些编程语言甚至阻止抽象类型被直接实例化），因为它们的唯一目的是作为一组相关类型的共同父类。 例如，假设我们想统一我们通过网络加载某些类型的模型的方式，通过提供一个共享的API，我们将能够用来分离关注点，使依赖注入和模拟变得容易，并在">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="Swift 中的抽象类型和方法">
<meta property="og:url" content="https://fanbaoying.github.io/Swift-中的抽象类型和方法/index.html">
<meta property="og:site_name" content="Swift社区">
<meta property="og:description" content="在面向对象的编程中，抽象类型提供了一个基础实现，其他类型可以从中继承，以获得某种共享的、共同的功能。抽象类型与普通类型的区别在于，它们永远不会被当作原样使用（事实上，一些编程语言甚至阻止抽象类型被直接实例化），因为它们的唯一目的是作为一组相关类型的共同父类。 例如，假设我们想统一我们通过网络加载某些类型的模型的方式，通过提供一个共享的API，我们将能够用来分离关注点，使依赖注入和模拟变得容易，并在">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2022-03-31T02:07:26.125Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Swift 中的抽象类型和方法">
<meta name="twitter:description" content="在面向对象的编程中，抽象类型提供了一个基础实现，其他类型可以从中继承，以获得某种共享的、共同的功能。抽象类型与普通类型的区别在于，它们永远不会被当作原样使用（事实上，一些编程语言甚至阻止抽象类型被直接实例化），因为它们的唯一目的是作为一组相关类型的共同父类。 例如，假设我们想统一我们通过网络加载某些类型的模型的方式，通过提供一个共享的API，我们将能够用来分离关注点，使依赖注入和模拟变得容易，并在">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://fanbaoying.github.io/Swift-中的抽象类型和方法/"/>





  <title>Swift 中的抽象类型和方法 | Swift社区</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/SwiftCommunityRes" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Swift社区</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">做最好的 Swift 社区</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://fanbaoying.github.io/Swift-中的抽象类型和方法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Swift社区">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/84354365?v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Swift社区">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Swift 中的抽象类型和方法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-03-31T10:03:26+08:00">
                2022-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index">
                    <span itemprop="name">Swift</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                -->
                <span title="字数统计">
                  数字统计 1,879字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                --> 

                <span title="阅读时长">
                  阅读时长 7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在面向对象的编程中，抽象类型提供了一个基础实现，其他类型可以从中继承，以获得某种共享的、共同的功能。抽象类型与普通类型的区别在于，它们永远不会被当作原样使用（事实上，一些编程语言甚至阻止抽象类型被直接实例化），因为它们的唯一目的是作为一组相关类型的共同父类。</p>
<p>例如，假设我们想统一我们通过网络加载某些类型的模型的方式，通过提供一个共享的API，我们将能够用来分离关注点，使<a href="https://www.swiftbysundell.com/articles/different-flavors-of-dependency-injection-in-swift" target="_blank" rel="noopener">依赖注入</a>和<a href="https://www.swiftbysundell.com/articles/mocking-in-swift" target="_blank" rel="noopener">模拟</a>变得容易，并在我们的项目中保持方法名称的一致性。</p>
<a id="more"></a>
<p>一个基于抽象类型的方法是使用一个基类，它将作为我们所有模型加载类型的共享、统一的接口。因为我们不希望这个类被直接使用，所以我们要让它在基类的实现被错误调用时触发一个<code>fatalError</code>:<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Loadable</span>&lt;<span class="title">Model</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">Model</span> &#123;</span><br><span class="line">        <span class="built_in">fatalError</span>(<span class="string">"load(from:) has not been implemented"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>然后，每个<code>Loadable</code>子类将重载上述<code>load</code>方法，以提供其加载功，如下所示：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserLoader</span>: <span class="title">Loadable</span>&lt;<span class="title">User</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">User</span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如果上述模式看起来很熟悉，那可能是因为它本质上与我们在<a href="https://www.swiftbysundell.com/basics/protocols" target="_blank" rel="noopener">Swift中通常使用的协议</a>的多态性完全相同。也就是说，当我们想定义一个接口，一个契约，多个类型可以通过不同的实现来遵守。</p>
<p>不过，协议确实比抽象类有一个显着的优势，因为编译器将强制它们的所有需求都得到正确实现——这意味着我们不再需要依赖运行时错误（例如 <code>fatalError</code>）来防止不当使用，因为我们无法实例化协议。</p>
<p>因此，如果我们采用面向协议的方案，而不是使用抽象基类，那么我们之前的 <code>Loadable</code> 和 <code>UserLoader</code> 类型可能看起来像这样：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">Loadable</span> </span>&#123;</span><br><span class="line">    associatedtype <span class="type">Model</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">Model</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserLoader</span>: <span class="title">Loadable</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">User</span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>请注意我们现在是如何使用一个相关的类型来使每个<code>Loadable</code>实现决定它想要加载的确切<code>Model</code>的——这给了我们一个在完全类型安全和巨大灵活性之间的很好的综合。</p>
<p>所以，一般来说，协议肯定是在Swift中声明抽象类型的首选方式，但这并不意味着它们是完美的。事实上，我们基于协议的<code>Loadable</code>实现目前有两个主要缺点:</p>
<ul>
<li><p>首先，由于我们不得不为我们的协议添加一个相关的类型，以保持我们的设计是泛型的和类型安全的，这意味着<code>Loadable</code>不能再<a href="https://www.swiftbysundell.com/questions/referencing-generic-protocols" target="_blank" rel="noopener">被直接引用了</a>。</p>
</li>
<li><p>其次，由于协议不能包含任何形式的存储。如果我们想添加任何存储属性，让所有的<code>Loadable</code>实现都能使用，我们就必须在每一个具体的实现中重新声明这些属性。</p>
</li>
</ul>
<p>这个属性存储方面确实是我们以前基于抽象类设计的一个巨大优势。因此，如果我们将<code>Loadable</code>还原成一个类，那么我们就能够将我们的子类所需要的所有对象直接存储在我们的基类中——不再需要在多种类型中重复声明这些属性：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Loadable</span>&lt;<span class="title">Model</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> networking: <span class="type">Networking</span></span><br><span class="line"><span class="keyword">let</span> cache: <span class="type">Cache</span>&lt;<span class="type">URL</span>, <span class="type">Model</span>&gt;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span>(networking: <span class="type">Networking</span>, cache: <span class="type">Cache</span>&lt;<span class="type">URL</span>, <span class="type">Model</span>&gt;) &#123;</span><br><span class="line">        <span class="keyword">self</span>.networking = networking</span><br><span class="line">        <span class="keyword">self</span>.cache = cache</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">Model</span> &#123;</span><br><span class="line">        <span class="built_in">fatalError</span>(<span class="string">"load(from:) has not been implemented"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserLoader</span>: <span class="title">Loadable</span>&lt;<span class="title">User</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">User</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">let</span> cachedUser = cache.value(forKey: url) &#123;</span><br><span class="line">            <span class="keyword">return</span> cachedUser</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> data = <span class="keyword">try</span> await networking.data(from: url)</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>所以，我们在这里处理的基本上是一个典型的权衡方案，两种方法（抽象类与协议）都给我们带来了不同的优点和缺点。但是，如果我们能把这两种方法结合起来，得到两个方案的优点，会怎么样呢？</strong></p>
<p>如果我们仔细想想，基于抽象类的方法唯一真正的问题是，我们必须在每个子类需要实现的方法中加入<code>fatalError</code>，那么如果我们只为这个特定的方法使用一个协议呢？那么我们仍然可以在基类中保留我们的<code>networking</code>和<code>cache</code>属性——像这样:<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">LoadableProtocol</span> </span>&#123;</span><br><span class="line">    associatedtype <span class="type">Model</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">Model</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoadableBase</span>&lt;<span class="title">Model</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> networking: <span class="type">Networking</span></span><br><span class="line"><span class="keyword">let</span> cache: <span class="type">Cache</span>&lt;<span class="type">URL</span>, <span class="type">Model</span>&gt;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span>(networking: <span class="type">Networking</span>, cache: <span class="type">Cache</span>&lt;<span class="type">URL</span>, <span class="type">Model</span>&gt;) &#123;</span><br><span class="line">        <span class="keyword">self</span>.networking = networking</span><br><span class="line">        <span class="keyword">self</span>.cache = cache</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>但这种方法的主要缺点是，所有的具体实现现在都必须对<code>LoadableBase</code>进行子类化，并声明它们符合我们新的<code>LoadableProtocol</code>协议：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserLoader</span>: <span class="title">LoadableBase</span>&lt;<span class="title">User</span>&gt;, <span class="title">LoadableProtocol</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这可能不是一个巨大的问题，但可以说它确实使我们的代码不那么优雅。不过，好消息是，我们实际上可以通过使用通用类型别名来解决这个问题。由于Swift的组合运算符<code>&amp;</code>支持将一个类和一个协议结合起来，我们可以将我们的<code>Loadable</code>类型作为<code>LoadableBase</code>和<code>LoadableProtocol</code>之间的组合重新引入：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typealias</span> <span class="type">Loadable</span>&lt;<span class="type">Model</span>&gt; = <span class="type">LoadableBase</span>&lt;<span class="type">Model</span>&gt; &amp; <span class="type">LoadableProtocol</span></span><br></pre></td></tr></table></figure></p>
<p>这样，具体的类型（如<code>UserLoader</code>）可以简单地声明它们是基于<code>Loadable</code>的，而编译器将确保所有这些类型实现我们协议的<code>load</code>方法——同时仍然使这些类型能够使用我们基类中声明的属性:<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserLoader</span>: <span class="title">Loadable</span>&lt;<span class="title">User</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">User</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">let</span> cachedUser = cache.value(forKey: url) &#123;</span><br><span class="line">            <span class="keyword">return</span> cachedUser</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> data = <span class="keyword">try</span> await networking.data(from: url)</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>很好! 上述方法的唯一真正的缺点是，<code>Loadable</code>仍然不能被直接引用，因为它仍然是部分的泛型协议。但这实际上可能不是一个问题——如果这成为一种情况，那么我们总是可以使用诸如<a href="https://xiaozhuanlan.com/topic/8295601734" target="_blank" rel="noopener">类型擦除</a>的技术来解决这些问题。</p>
<p>对于我们新的基于类型别名的<code>Loadable</code>设计方案，另一个轻微的警告是这种组合类型别名不能被扩展，如果我们想提供一些我们不想（或不能）在<code>LoadableBase</code>类中直接实现的便利API，这可能会成为一个问题。</p>
<p>不过，解决这个问题的一个方法是，在我们的协议中声明实现这些便利API所需要的一切，这将使我们能够自行扩展该协议：<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">LoadableProtocol</span> </span>&#123;</span><br><span class="line">    associatedtype <span class="type">Model</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> networking: <span class="type">Networking</span> &#123; <span class="keyword">get</span> &#125;</span><br><span class="line"><span class="keyword">var</span> cache: <span class="type">Cache</span>&lt;<span class="type">URL</span>, <span class="type">Model</span>&gt; &#123; <span class="keyword">get</span> &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">load</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">Model</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">LoadableProtocol</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">loadWithCaching</span><span class="params">(from url: URL)</span></span> async <span class="keyword">throws</span> -&gt; <span class="type">Model</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">let</span> cachedModel = cache.value(forKey: url) &#123;</span><br><span class="line">            <span class="keyword">return</span> cachedModel</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> model = <span class="keyword">try</span> await load(from: url)</span><br><span class="line">        cache.insert(model, forKey: url)</span><br><span class="line">        <span class="keyword">return</span> model</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这就是在Swift中使用抽象类型和方法的几种不同方式。子类化目前可能不像以前那样流行（在其他编程语言中也是如此），但我仍然认为这些技术在我们整个Swift开发工具箱中是非常好的。</p>
<p>感谢您的阅读 🚀</p>
<blockquote>
<p>译自 John Sundell 的 <a href="https://www.swiftbysundell.com/articles/abstract-types-and-methods/" target="_blank" rel="noopener">Abstract types and methods in Swift</a></p>
</blockquote>

      
    </div>
    
    
    
    

    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    


    
      <div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/Swift-中的抽象类型和方法/">Swift 中的抽象类型和方法</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Swift社区 的个人博客">Swift社区</a></p>
  <p><span>发布时间:</span>2022年03月31日 - 10:03</p>
  <p><span>最后更新:</span>2022年03月31日 - 10:03</p>
  <p><span>原始链接:</span><a href="/Swift-中的抽象类型和方法/" title="Swift 中的抽象类型和方法">https://fanbaoying.github.io/Swift-中的抽象类型和方法/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://fanbaoying.github.io/Swift-中的抽象类型和方法/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      </div>
    


    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="Swift社区 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Swift社区 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"><i class="fa fa-tag"></i> iOS</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/Swift-中风味各异的类型擦除/" rel="next" title="Swift 中风味各异的类型擦除">
                <i class="fa fa-chevron-left"></i> Swift 中风味各异的类型擦除
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/LeetCode-24-两两交换链表中的节点/" rel="prev" title="LeetCode - 24 两两交换链表中的节点">
                LeetCode - 24 两两交换链表中的节点 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars.githubusercontent.com/u/84354365?v=4"
                alt="Swift社区" />
            
              <p class="site-author-name" itemprop="name">Swift社区</p>
              <p class="site-description motion-element" itemprop="description">我们的使命是做一个最专业最权威的 Swift 中文社区，我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货，不忘初心，牢记使命。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">187</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36478920" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a30d987f265da430d580126" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-spinner"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/fanbaoying" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/swift-community" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/7711465033" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzAxNzgzNTgwMw==&action=getalbum&album_id=2024314764775981057" target="_blank" title="公众号">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftWeekly" title="SwiftWeekly" target="_blank">SwiftWeekly</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/article-ios" title="Article-ios" target="_blank">Article-ios</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftUI-Book" title="SwiftUI-Book" target="_blank">SwiftUI-Book</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Swift社区</span>

  
</div>

<!-- 
<div class="powered-by">
  <i class="fa fa-user-md">
  </i>
  <span id="busuanzi_container_site_uv">
    已有<span id="busuanzi_value_site_uv"></span>人来访
  </span>

</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
  <i class="fa fa-eye"></i>
  <span id="busuanzi_container_site_pv">
      访问量<span id="busuanzi_value_site_pv"></span>次
  </span>
</div>



  <span class="post-meta-divider">|</span>


-->

<div class="theme-info">
  <i class="fa fa-pencil"></i>
  <span class="post-count">博客全站共361.6k字</span>
</div>


<!-- 
  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
